#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <pthread.h>


#ifndef _POSIX_THREAD_PROCESS_SHARED
#error "This platform does not support process shared mutex"
#endif

int shared_mem_id;
pthread_mutex_t *mptr;
pthread_mutexattr_t mutex_shared_attr;

int main(void){
	int status;

	shared_mem_id = shmget(IPC_PRIVATE, 1 * sizeof(pthread_mutex_t), 0660);
	if(shared_mem_id == -1){
		perror("create shared memory failed.");
		exit(-1);
	}
	void *shared_mem_ptr = shmat(shared_mem_id, (void*)0, 0);
	mptr = shared_mem_ptr;
	pthread_mutexattr_init(&mutex_shared_attr);
	pthread_mutexattr_setpshared(&mutex_shared_attr, PTHREAD_PROCESS_SHARED);
	pthread_mutex_init(mptr, &mutex_shared_attr);
	pthread_mutexattr_destroy(&mutex_shared_attr);
	int parent_pid = getpid();
	fork();
	int current_pid = getpid();
	if (current_pid == parent_pid){
		printf("current process is parent process: %d.\n", current_pid);
	}else{
		printf("current process is child process: %d.\n", current_pid);
	}
	for(int i = 0; i < 100; i++){
		pthread_mutex_lock(mptr);
		usleep(5000);
		printf("pid: %d, current i: %d\n", current_pid, i);
		pthread_mutex_unlock(mptr);
	}
	if (pthread_mutex_destroy(mptr)){
		printf("pthread_mutex_destroy failed: %d\n", current_pid);
		exit(-1);
	}else{
		printf("pthread_mutex_destroy success: %d\n", current_pid);
	}
}
